import { makeAutoObservable } from 'mobx';
import * as api from './api';
import * as dict from '@/services/dict';

import { MAGIC_NUMBERS } from './definitions';


class TableArgs {
  constructor(query) {
    this._args = {
      search: {},
      pg: {
        page: 0,
        sort: ['crDate;desc'],
        size: 10,
      },
    };
    this.loading = false;
    this.total = 0;
    this.dataSource = [];
    this.refundData = [];
    this.isView = false;
    this.query = query;
    this._orderRefundStatus = '0';
    this._orderABRefundStatus = '0';
    this.accounts = []; // 分账原数据
    this.accountB = []; // 分账原数据
    this.initAccountsA = []; // A段分账方数据
    this.initAccountsB = []; // B段分账方数据
    this.currentRequestId = null;
    makeAutoObservable(this, {});
  }
  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
export default class CcOrderStore {
  loadingLogs = false;
  _orderRefundStatus = '0';
  _orderABRefundStatus = '0'
  _tabKey = '0';

  _mainArgs = new TableArgs(this.query);
  _commentArgs = new TableArgs(this.getComment);

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  get api() {
    return api;
  }

  get tabKey() {
    return this._tabKey;
  }

  set tabKey(value) {
    this._tabKey = value;
    this._mainArgs._tabKey = value;
    // this._mainArgs._args.pg.page = 0;
    // this._mainArgs.query({ page: 0 });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    if (this._tabKey === '1') {
      search.queryCancel = true;
    }
    this.loading = true;
    const requestId = new Date().getTime(); // 生成新的唯一标识符
    this.currentRequestId = requestId;

    try {
      // eslint-disable-next-line no-nested-ternary
      const total = this._tabKey === '1'
        ? yield api.getOrderTicketCount({ search })
        : (this.isView ? yield api.ordersSearchCount({ search }) : yield api.count({ search }));

      // eslint-disable-next-line no-nested-ternary
      const orders = this._tabKey === '1'
        ? yield api.getOrderTicket({ search, pg })
        : (this.isView ? yield api.ordersSearch({ search, pg }) : yield api.search({ search, pg }));

      if (this.currentRequestId === requestId) { // 确保响应是当前的请求
        this.total = total;
        this.dataSource = orders;
      }
    } finally {
      if (this.currentRequestId === requestId) {
        this.loading = false;
      }
    }
  }

  * get(orderId) {
    return yield api.get(orderId);
  }

  * getLogs(order) {
    const { taskIds: taskIdsTmp = [], id } = order;
    const taskIds = [...new Set(taskIdsTmp)];
    const orderSearch = {
      targetType: 'ccOrder',
      targetIds: [...taskIds, id],
    };
    this.loadingLogs = true;
    try {
      const orderLogs = yield api.getLogs(orderSearch);
      const taskLogs = [];
      for (const taskId of taskIds) {
        const taskInfo = yield api.getTaskInfo(taskId);
        const { driverInfo = [], carrierCompanyName } = toJS(taskInfo);
        // 获取任务涉及的工单id
        const workOrderIds = driverInfo.reduce((res, cur) => {
          const { number } = cur;
          res.push(number);
          return res;
        }, []);

        const taskSearch = {
          targetIds: [...workOrderIds, taskId],
        };
        const taskLogRes = yield api.getLogs(taskSearch);
        taskLogs.push({
          taskId,
          taskLog: toJS(taskLogRes),
          companyName: carrierCompanyName,
        });
      }
      return { orderLogs, taskLogs };
    } finally {
      this.loadingLogs = false;
    }
  }

  * getTaskLogs(curDriverInfo) {
    const { driverId, number: taskOrderId } = curDriverInfo || {};
    if (driverId && taskOrderId) {
      return yield api.getLogTime(taskOrderId, driverId);
    }
  }

  /**
   * @func 获取当前订单任务数据
   * @param {object} order 订单数据
   * @return {object} 任务数据
   */
  * getTask(order) {
    const { taskIds, id: orderId } = order || {};
    const { directRoute } = order?.ccOrder || {};
    if (directRoute) {
      return yield api.getTaskInfo(taskIds[0]);
    } else {
      return yield api.getTransferTaskInfo(orderId);
    }
  }

  /**
   * @func 获取当前订单评论
   * @desc
   * @param {}
   * @return {}
   */
  * getComment(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined));
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.commentCount(search);
      this.dataSource = yield api.commentSearch(search, pg);
    } finally {
      this.loading = false;
    }
  }

  * update(order) {
    yield api.update(order);
    this.query();
  }

  * orderSponsorRefund(id, order, args) {
    yield api.orderSponsorRefund(id, order, args);
    this.query();
  }

  * getIdRefund(id, order) {
    const data = yield api.getIdRefund(id, order);
    const promiseAry = data.map((p) => api.get(p?.orderInfo?.orderId)
      .then((r) => ({ ...p, order: r })));
    return Promise.all(promiseAry);
  }

  * cancel(id) {
    yield api.cancel(id);
    this._mainArgs.query();
  }

  * getAccount(id, type) {
    return yield api.getAccount(id, type);
  }

  * getTransferLine(id) {
    return yield api.getTransferLine(id);
  }

  * orderCreateOffline(data) {
    return yield api.orderCreateOffline(data);
  }

  * orderCancelRefund(args) {
    const { applicationId, orderInfo } = args;
    yield api.orderCancelRefund({ applicationId, orderId: orderInfo.orderId });
    this.query();
  }

  * orderCommitRefund(args) {
    const { applicationId, orderInfo } = args;
    yield api.orderCommitRefund({ applicationId, orderId: orderInfo.orderId });
    this.query();
  }

  * orderRefundUpdate(order) {
    yield api.orderRefundUpdate(order);
    this.query();
  }

  * getOrderDiscountInfo(args) {
    return yield api.getOrderDiscountInfo(args);
  }

  * orderCancel(args) {
    yield api.orderCancel(args);
    this._mainArgs.query();
  }

  * orderEnableShare(args) {
    yield api.orderEnableShare(args);
    this._mainArgs.query();
  }

  * getDictItem(dictId, itemId) {
    return yield dict.getDictItem(dictId, itemId);
  }

  ticIdx(i) {
    return 0 * 10 + i + 1;
  }

  get orderRefundStatus() {
    return this._orderRefundStatus;
  }

  set orderRefundStatus(value) {
    this._orderRefundStatus = value;
    this._mainArgs.pg.page = 0;
    this._mainArgs.query({ page: 0 });
  }

  get orderABRefundStatus() {
    return this._orderABRefundStatus;
  }

  set orderABRefundStatus(value) {
    this._orderABRefundStatus = value;
  }

  getDriverInfo(driverInfo = []) {
    const { DRIVER_STATE } = MAGIC_NUMBERS;
    if (driverInfo.length <= 0) return {};
    const curDriver = driverInfo.find((e) => e.state !== DRIVER_STATE.CANCEL);
    return curDriver;
  }

  /**
   * @func 获取商户信息
   * @desc 获取商户自定义附加费
   * @param {}
   * @return {}
  */
  * getMerchantInfo(merchantId) {
    return yield api.getMerchants(merchantId);
  }

  * offlineAddPay(merchantId) {
    yield api.offlineAddPay(merchantId);
    yield this._mainArgs.query();
  }

  async getOrderPayee(args) {
    try {
      return await api.getOrderPayee(args);
    } catch (error) {
      console.log('🚀 _ file: CcOrderStore.js:320 _ CcOrderStore _ getOrderPayee _ error:', error);
      throw error;
    }
  }

  transferSupplementParams(order, params) {
    const { id, username, ccOrder, reason } = toJS(order);
    const { subscribeName } = ccOrder;
    const { payee, resultAccount } = params;
    const _distributeInfos = [];
    let amountTotal = 0;
    for (let i = 0; i < resultAccount.length; i++) {
      const { targetId, targetName, targetType, amount = 0 } = resultAccount[i];
      const _amount = amount * 100;
      _distributeInfos.push({ targetId, targetName, targetType, amount: _amount });
      amountTotal += _amount;
    }

    const args = {};
    _.assign(args, {
      orderId: id,
      payOffline: {
        id,
        outTradeNo: id,
        subOutTradeNo: id,
        payee,
        reason,
        payer: {
          targetId: username,
          targetName: subscribeName,
          targetType: 'CUSTOMER',
        },
        amount: amountTotal,
      },
      distributeInfos: _distributeInfos,
    });

    return args;
  }
}
